// 医嘱标本
import React from 'react';
import { Form, Icon, Select, Button, DatePicker, message, Popconfirm, Checkbox } from 'antd';
import { $http } from 'containers/config/https';
import '../style/childStyle.less';
import Moment from 'moment';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

const { Option } = Select;

class OLSpecimensDoctorAdvice extends React.Component {
    constructor() {
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            selectData: {}, // 下拉框数据
            hosp: undefined, // 医院
            status: true, // 仅显示生效
            tableData: [], // 列表数据
            total: 0,
            page: 1,
            pageSize: 10,
            rowData: {}, // 编辑回显数据
            user: userData,
            medID: '',
            specID: undefined,
            loading: false
        };
        this.columns = [
            {
                key: 1,
                title: '序号',
                dataIndex: 'key',
                align: "center",
                width: '15%'
            },
            {
                key: 2,
                title: '医院',
                dataIndex: 'hospDesc',
                align: "center",
                width: '25%'
            },
            {
                key: 3,
                title: '标本',
                dataIndex: 'specDesc',
                align: "center",
                width: '25%'
            },
            {
                key: 4,
                title: '状态',
                dataIndex: 'status',
                align: "center",
                width: '15%'
            },
            {
                title: '操作',
                key: 5,
                align: "center",
                width: '20%',
                render: (text, record) => (
                    <span>
                        <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                        </Popconfirm>
                    </span>
                ),
            }
        ];
    }

    componentDidMount() {
        this.getSelectData();
        if ((this.props.medData && this.props.medData.medID ? this.props.medData.medID : '') !== this.state.medID) {
            this.setState({ medID: this.props.medData.medID }, () => {
                this.handleQuery();
            })
        } else {
            this.child.handleLoading();
        }
    }

    componentWillReceiveProps(nextProps) {
        if ((nextProps.medData && nextProps.medData.medID ? nextProps.medData.medID : '') !== this.state.medID) {
            this.setState({ medID: nextProps.medData.medID }, () => {
                this.handleQuery();
            })
        }
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }
    compilePage = (page, pageSize) => {
        this.setState({
            page,
            pageSize,
        }, () => {
            this.getTableData()
        })

    }
    // 获取下拉框数据
    getSelectData = () => {
        let { user } = this.state;
        let data = {
            params: [{
                logonHospID: user.hospID,
                logonGroupID: user.groupID,
                hospFlag: 'Y',
                specFlag: 'Y'
            }]
        }
        $http.post('urlS', this, {
            code: "03010037",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    this.setState({ selectData: res.result })
                }
            }
        })
    }

    // 请求列表数据
    getTableData() {
        this.setState({ loading: true });
        let { page, pageSize, status, hosp, user, medID, specID } = this.state;
        let data = {
            params: [{
                medID, // 医嘱项id
                active: status ? 'Y' : 'N', // 状态
                hospID: hosp, // 医院
                userID: user.userID,
                logonHospID: user.hospID,
                groupID: user.groupID,
                specID
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "Describe",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: "03010033",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    for (var i = 0; i < res.result.data.length; i++) {
                        res.result.data[i].key = i + 1
                    }
                    this.setState({ tableData: res.result.data, total: res.result.totalCount, loading: false }, () => {
                        // 数据加载成功关闭loading
                        this.child.handleLoading();
                    })
                } else {
                    this.setState({ tableData: [], total: 0, loading: false }, () => {
                        // 数据加载成功关闭loading
                        this.child.handleLoading();
                    })
                }
            },
            error: function () {
                this.setState({ tableData: [], total: 0, loading: false }, () => {
                    // 数据加载成功关闭loading
                    this.child.handleLoading();
                })
            }
        })
    }

    // 查询
    handleQuery = () => {
        this.setState({ page: 1, pageSize: 10 }, () => {
            this.getTableData();
        })
    }

    handleHospID = e => {
        this.setState({ hosp: e }, () => {
            this.handleQuery();
        })
    }

    handleSpecID = e => {
        this.setState({ specID: e }, () => {
            this.handleQuery();
        })
    }

    // 是否生效
    handleCheckbox = e => {
        this.setState({ status: e.target.checked }, () => {
            this.handleQuery();
        })
    }
    // 重置
    resetFields = () => {
        this.props.form.resetFields(); //清空所有
        this.setState({
            rowData: {}
        })
    }
    // 保存
    handleSave = () => {
        const { form: { validateFields } } = this.props;
        let { user, medID, rowData } = this.state;
        validateFields((errors, values) => {
            if (errors === null) {
                let data = {
                    params: []
                };
                let obj = JSON.parse(JSON.stringify(values));
                obj.id = rowData && rowData.id ? rowData.id : '';
                obj.userID = user.userID;
                obj.logonHospID = user.hospID;
                obj.groupID = user.groupID;
                obj.medID = medID; // 医嘱项id
                obj.startDate = obj.startDate ? Moment(obj.startDate).format("YYYY-MM-DD") : '';
                obj.stopDate = obj.stopDate ? Moment(obj.stopDate).format("YYYY-MM-DD") : '';
                data.params.push(obj);
                $http.post('urlADS', this, {
                    code: '03010031',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success(rowData && rowData.id ? '编辑成功' : '新增成功');
                            this.handleQuery();
                            this.resetFields();
                        }
                    }
                })
            }
        })
    }

    // 重置
    resetFields = () => {
        this.props.form.resetFields(); //清空所有
        this.setState({
            rowData: {}
        })
    }

    // 删除
    handleDelete = record => {
        let { user } = this.state;
        let data = {
            params: [{
                id: record.id,
                userID: user.userID,
                logonHospID: user.hospID,
                groupID: user.groupID,
            }]
        }
        $http.post('urlADS', this, {
            code: '03010032',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('删除成功');
                    // 刷新列表数据
                    this.getTableData();
                }
            }
        })
    }

    render() {
        let { selectData, hosp, status, tableData, total, page, rowData, specID, loading } = this.state;
        const { getFieldDecorator } = this.props.form;
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.columns,
            // 表格数据
            data: tableData,
            // 数据总条数
            total: total,
            // 当前页数
            page: page,
            // 表格的宽度
            x: 900,
            y: 360,
            TableClassName: "ols",
            height: '400px',
            loading
        };

        // 医院
        let hospOption = selectData.hosp && selectData.hosp.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 标本
        let specOption = selectData.spec && selectData.spec.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        return (
            <div className="associated">
                <div>
                    <div style={{ background: 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', fontWeight: '700' }}>
                        添加标本
                        <span style={{ fontSize: '12px', color: '#157EDF', fontWeight: '100', marginLeft: '10px' }}>(说明：未选择医院代表所有使用该医嘱项的医院均可使用该检查标本)</span>
                    </div>
                    <div>
                        <Form>
                            <Form.Item label="医院：">
                                {getFieldDecorator('hospID', {
                                    initialValue: rowData.hospID ? rowData.hospID : undefined,
                                })(
                                    <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '120px', marginRight: '8px' }} placeholder="请选择">
                                        {hospOption}
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item label="检查标本：">
                                {getFieldDecorator('specID', {
                                    initialValue: rowData.specID ? rowData.specID : undefined,
                                    rules: [{ required: true, message: '检查标不能为空' }]
                                })(
                                    <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '120px', marginRight: '8px' }} placeholder="请选择">
                                        {specOption}
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item label="生效日期：">
                                {getFieldDecorator('stDate', {
                                    initialValue: rowData.stDate ? rowData.stDate : undefined,
                                    rules: [{ required: true, message: '生效日期不能为空' }]
                                })(
                                    <DatePicker style={{ width: '120px', marginRight: '8px' }} format="YYYY-MM-DD" allowClear />
                                )}
                            </Form.Item>
                            <Form.Item label="失效日期：">
                                {getFieldDecorator('endDate', {
                                    initialValue: rowData.endDate ? rowData.endDate : undefined,
                                })(
                                    <DatePicker style={{ width: '120px', marginRight: '8px' }} format="YYYY-MM-DD" allowClear />
                                )}
                            </Form.Item>
                            <span style={{ display: 'inline-block', margin: '4px 8px 0 0' }}>
                                <Button type="primary" onClick={this.handleSave}>保存</Button>
                            </span>
                            <span style={{ display: 'inline-block', marginTop: '4px' }}>
                                <Button onClick={this.resetFields}>清空</Button>
                            </span>
                        </Form>
                    </div>
                </div>
                <div>
                    <div style={{ background: 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', fontWeight: '700' }}>
                        已添加标本
                        <span style={{ float: 'right', fontWeight: '100' }}>
                            <Select value={hosp} onChange={this.handleHospID} onPressEnter={this.handleHospNameEnter} showSearch optionFilterProp="seatchprop" allowClear style={{ width: '200px', marginRight: '8px' }} placeholder="根据医院过滤数据">
                                {hospOption}
                            </Select>
                            <Select value={specID} onChange={this.handleSpecID} onPressEnter={this.handleHospNameEnter} showSearch optionFilterProp="seatchprop" allowClear style={{ width: '100px', marginRight: '8px' }} placeholder="标本名称">
                                {specOption}
                            </Select>
                            <Checkbox checked={status} onChange={this.handleCheckbox} style={{ fontSize: '12px', color: '#000' }}>仅显示生效</Checkbox>
                        </span>
                    </div>
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                </div>
            </div>
        )
    }
};
const OLSpecimensDoctorAdviceForm = Form.create()(OLSpecimensDoctorAdvice);
export default OLSpecimensDoctorAdviceForm;